package com.ruoyi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.entity.ChartQueryDTO;
import com.ruoyi.entity.ExcelData;
import com.ruoyi.service.RagFlowService;
import com.ruoyi.utils.Convert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.*;

@Slf4j
@Service
public class RagFlowServiceImpl implements RagFlowService {


    @Value("${ai.address}")
    private String ragflowAddress;

    @Value("${ai.your_api_key}")
    private String apiKey;

    @Value("${ai.chat_id}")
    private String chatId;

    @Value("${ai.timeout}")
    private int timeout;

    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(timeout, TimeUnit.MILLISECONDS)
            .readTimeout(timeout, TimeUnit.MILLISECONDS)
            .build();
    @Override
    public ExcelData fetchExcelData(ChartQueryDTO query) {
        try {
            // 构建认证请求头
            Headers headers = new Headers.Builder()
                    .add("Authorization", apiKey)
                    .add("Chat-ID", chatId)
                    .build();

            // 构造请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("query", buildSearchQuery(query));
            requestBody.put("data_source", query.getDataSource());

            Request request = new Request.Builder()
                    .url(ragflowAddress + "/api/v1/search")
                    .post(RequestBody.create(
                            requestBody.toJSONString(),
                            MediaType.parse("application/json")))
                    .headers(headers)
                    .build();

            // 执行请求
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new IOException("RAGFlow响应异常: " + response.code());
                }
                return parseResponse(response.body().string());
            }
        } catch (Exception e) {
            log.error("RAGFlow数据获取失败: {}", e.getMessage());
            throw new RuntimeException("数据服务暂不可用");
        }
    }

    private String buildSearchQuery(ChartQueryDTO query) {
        StringBuilder sb = new StringBuilder();
        sb.append("[用户需求]\n")
                .append(query.getQuery())
                .append("\n\n")
                .append("[附加要求]\n")
                .append("1. 数据范围：")
                .append(query.getStartDate() != null ? query.getStartDate().toString() : "无")
                .append(" ~ ")
                .append(query.getEndDate() != null ? query.getEndDate().toString() : "无")
                .append("\n")
                .append("2. 数据格式：Excel标准格式\n")
                .append("3. 包含字段：产品名称、销售额、日期");
        return sb.toString();
    }

    private ExcelData parseResponse(String responseBody) {
        JSONObject json = JSON.parseObject(responseBody);

        ExcelData data = new ExcelData();
        data.setHeaders(json.getJSONArray("headers").toJavaList(String.class));

        JSONArray rows = json.getJSONArray("rows");
        List<Map<String, Object>> rowList = new ArrayList<>();

        for (int i = 0; i < rows.size(); i++) {
            JSONObject row = rows.getJSONObject(i);
            Map<String, Object> rowMap = new HashMap<>();

            row.keySet().forEach(key -> {
                Object value = row.get(key);
                // 处理Excel特殊数值格式
                if (key.endsWith("Date")) {
                    rowMap.put(key, Convert.excelNumberToDate((Double) value));
                } else {
                    rowMap.put(key, value);
                }
            });

            rowList.add(rowMap);
        }

        data.setRows(rowList);
        return data;
    }
}
